<?php
declare (strict_types=1);

namespace app\course\logic\courseware\admin;

use app\common\exception\LogicException;
use app\course\model\courseware\admin\Courseware as CoursewareModel;
use think\facade\Request;

/**
 * Class Courseware
 *
 * @package app\course\logic\courseware\admin
 */
class Courseware extends CoursewareModel
{
    /**
     * 获取列表
     *
     * @param array $map
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $map = [])
    {
        return $this->with(['course', 'attach'])->where($map)->order('create_time', 'desc')->paginate($this->getListRows());
    }

    /**
     * 添加课件
     *
     * @param int $courseId
     * @param     $data
     * @return int
     */
    public function created(int $courseId, $data)
    {
        $data['course_id'] = $courseId;
        // 验证数据
        $this->getValidate()->failException()->check($data);

        $attachIds = $data['attach_id'];
        if (is_array($attachIds)) {
            $insert = [];
            foreach ($attachIds as $attachId) {
                $insert[] = [
                    'attach_id'   => $attachId,
                    'course_id'   => $courseId,
                    'create_time' => Request::time()
                ];

            }

            return $this->insertAll($insert);
        }

        if (!$this->data($data, true)->save()) {
            throw new LogicException('添加失败');
        }

        return 1;
    }

    /**
     * 移除课件
     *
     * @param int $courseId
     * @param int $coursewareId
     */
    public function deleted(int $courseId, int $coursewareId)
    {
        $link = $this->where('course_id', $courseId)
            ->where('id', $coursewareId)
            ->findOrFail();
        if (!$link->delete()) {
            throw new LogicException("移除失败");
        }
    }

}